package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.NursingTaskMapper;
import com.zzyl.nursing.service.INursingTaskService;
import com.zzyl.nursing.vo.NursingTaskVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 护理任务Service业务层处理
 *
 * @author dyl
 * @date 2025-06-06
 */
@Service
@Slf4j
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper, NursingTask> implements INursingTaskService {
    @Autowired
    private NursingTaskMapper nursingTaskMapper;

    private Elder elder;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询护理任务
     *
     * @param id 护理任务主键
     * @return 护理任务
     */
    @Override
    public NursingTaskVo selectNursingTaskById(Long id) {
        NursingTask nursingTask = nursingTaskMapper.selectNursingTaskById(id);

        if (nursingTask == null) {
            throw new RuntimeException("护理任务不存在");
        }
        NursingTaskVo nursingTaskVo = BeanUtil.toBean(nursingTask, NursingTaskVo.class);

        Elder elder = elderMapper.selectById(nursingTask.getElderId());
        CheckIn checkIn = checkInMapper.selectByIdA(elder.getId());
        log.info("查询护理等级: NursingLevelName={}, id={}", checkIn.getNursingLevelName(),checkIn.getId());
        nursingTaskVo.setNursingLevelName(checkIn.getNursingLevelName());
        if (elder != null && StringUtils.isNotBlank(elder.getIdCardNo())) {
            // 4. 计算年龄并设置到VO中
            try {
                int age = calculateAgeFromIdCard(elder.getIdCardNo());
                nursingTaskVo.setAge(age);
            } catch (IllegalArgumentException e) {
                log.warn("计算年龄失败，老人ID：{}，身份证号：{}", elder.getId(), elder.getIdCardNo());
                nursingTaskVo.setAge(null);
            }
        }
        return nursingTaskVo;

    }

    public int calculateAgeFromIdCard(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            throw new IllegalArgumentException("无效的身份证号");
        }
        // 提取出生日期部分（第7-14位）
        String birthDateStr = idCard.substring(6, 14);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
        LocalDate currentDate = LocalDate.now();

        return Period.between(birthDate, currentDate).getYears();
    }


    /**
     * 查询护理任务列表
     *
     * @param nursingTask 护理任务
     * @return 护理任务
     */
    @Override
    public List<NursingTask> selectNursingTaskList(NursingTask nursingTask) {
        return nursingTaskMapper.selectNursingTaskList(nursingTask);
    }

    /**
     * 新增护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int insertNursingTask(NursingTask nursingTask) {
        return save(nursingTask) ? 1 : 0;
    }

    /**
     * 修改护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(NursingTask nursingTask) {
        return updateById(nursingTask) ? 1 : 0;
    }

    /**
     * 批量删除护理任务
     *
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除护理任务信息
     *
     * @param id 护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void cancelNursingTask(NursingTaskCancel cancel) {
        NursingTask nursingTask = getById(cancel.getTaskId());
        if (nursingTask == null) {
            log.error("取消护理任务失败，未找到该任务");
            return;
        }
        if (nursingTask.getStatus() == 3) {
            log.error("取消护理任务失败，该任务已取消");
            return;
        }

        NursingTask update = new NursingTask();
        update.setId(cancel.getTaskId());
        update.setStatus(3);
        update.setCancelReason(cancel.getReason());
        updateById(update);
        log.info("取消护理任务成功,id={}", cancel.getTaskId());

    }

    @Override
    public NursingTaskDo doNursingTask(NursingTaskDo nursingTaskDo) {
        NursingTask nursingTask = getById(nursingTaskDo.getTaskId());
        if (nursingTask == null) {
            log.info("任务不存在");
            return nursingTaskDo;
        }
        if (nursingTask.getStatus() != 1) {
            log.info("任务状态错误");
            return nursingTaskDo;
        }
        NursingTask update = new NursingTask();
        update.setStatus(2);
        update.setEstimatedServerTime(nursingTask.getEstimatedServerTime());
        update.setId(nursingTaskDo.getTaskId());
        update.setMark(nursingTaskDo.getMark());
        update.setTaskImage(nursingTaskDo.getTaskImage());
        updateById(update);
        log.info("更新任务状态成功,id={}", nursingTaskDo.getTaskId());
        return nursingTaskDo;
    }

    @Override
    public NursingTaskUpdateTime updateTimeNursingTask(NursingTaskUpdateTime nursingTaskUpdatetime) {
        NursingTask nursingTask = getById(nursingTaskUpdatetime.getTaskId());
        if (nursingTask == null) {
            log.error("更新任务时间失败,id={}", nursingTaskUpdatetime.getTaskId());
            return null;
        }
        if (nursingTask.getStatus() != 1) {
            log.error("更新任务时间失败,任务状态不是待执行");
            return null;
        }
        NursingTask update = new NursingTask();
        update.setId(nursingTaskUpdatetime.getTaskId());
        update.setEstimatedServerTime(nursingTaskUpdatetime.getEstimatedServerTime());
        updateById(update);
        log.info("更新任务时间成功,id={}", nursingTaskUpdatetime.getTaskId());
        return nursingTaskUpdatetime;
    }
}
